package fun.stgoder.test1;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class TestSemaphore {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(1);

        new Thread(() -> {

            while (true) {
                try {
                    semaphore.acquire();
                    System.out.println("1 begin");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println("1 finish");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }


                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        }).start();

        new Thread(() -> {

            while (true) {
                try {
                    semaphore.acquire();
                    System.out.println("2 begin");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println("2 finish");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }


                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        }).start();
    }
}
